package com.stratosgear.gmaptests;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.beoui.geocell.GeocellManager;
import com.beoui.geocell.GeocellUtils;
import com.beoui.geocell.model.BoundingBox;
import com.beoui.geocell.model.Point;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;

@SuppressWarnings("serial")
public class GetGeohashBounds extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		double lat = Double.parseDouble(req.getParameter("lat"));
		double lon = Double.parseDouble(req.getParameter("lng"));

		// Transform it to a point
		Point p = new Point(lat, lon);

		// Generates the list of GeoCells
		List<String> cells = GeocellManager.generateGeoCell(p);

		JSONArray bounds = new JSONArray();

		try {
			for (int i = 0; i < cells.size(); i++) {
				JSONArray aBound = new JSONArray();

				BoundingBox box = GeocellUtils.computeBox(cells.get(i));
				double east = box.getEast();
				double south = box.getSouth();
				double west = box.getWest();
				double north = box.getNorth();
				double width = GeocellUtils.distance(box.getNorthEast(), new Point(box.getNorth(), box.getWest()));
				double height = GeocellUtils.distance(box.getNorthEast(), new Point(box.getSouth(), box.getEast()));

				aBound.put(cells.get(i));
				aBound.put(east);
				aBound.put(south);
				aBound.put(west);
				aBound.put(north);
				aBound.put(width);
				aBound.put(height);

				bounds.put(aBound);

			}

			resp.setContentType("text/plain");
			resp.getWriter().println(bounds.toString(2));
		}
		catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
